package com.moyun.syssecurity.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName MyParallelismSessionExpiredStrategy
 * @Description Session 会话 并行配置 失效策略,用于返回异常信息
 *
 * @Author yangboxuan
 * @Date 2021/7/4 10:25
 */
@Slf4j
@RequiredArgsConstructor
public class MyParallelismSessionExpiredStrategy implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
        // 返回异常信息
        SessionInformation sessionInformation = (SessionInformation) event.getSource();
        log.info("触发Session并发会话配置失效策略.触发的用户{}",sessionInformation.getPrincipal().toString());
        event.getResponse().setContentType("application/json;charset=UTF-8");
        PrintWriter out = event.getResponse().getWriter();
        out.print("{\"code\":\"1\",\"msg\":\" 您的登录状态已过期(账号已在另一台设备登录).如有需要,请重新登录! \"}");
        out.flush();
        out.close();

    }
}
